package com.kgd.news.controller.admin;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
import com.kgd.news.entity.*;
import com.kgd.news.utils.Api;
import com.kgd.news.utils.BaseController;
import com.kgd.news.utils.Config;
import com.kgd.news.utils.StringUtils;
import com.kgd.news.utils.db.DbSychronizationController;
import com.kgd.news.utils.wx.WxHelper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/10/9
 * @Time: 下午3:03
 */
public class DbtableController extends BaseController {
    @Override
    public void list() {
        String title = getPara("title");
        String categoryid = getPara("categoryid");
        String type = "dbtable";
        String sql = "from dbtable where 1=1 ";
        if (!StringUtils.isEmpty(title)) {
            sql += " and title like '%" + title + "%'";
            type += title;
        }
        if (!StringUtils.isEmpty(categoryid)) {
            if ("-1".equals(categoryid)) {
                sql += " and category is null";
            } else {
                sql += " and category =" + categoryid;
            }
            type += categoryid;
        }
        Page<Dbtable> data = Dbtable.dao.paginate(getPageIndex(type), 40, "select *", sql);
        setAttr("data", data);
        setAttr("categoryid", categoryid);
        render("dbtable_list.html");
    }

    public void listDialog() {
        String content_ids = getPara("content_ids");
        String table = getPara("table");
        String title = getPara("title");
        String copyType = getPara("copyType");
        String categoryid = getPara("categoryid");
        String type = "dbtable_dialog";
        String sql = "from dbtable where 1=1 ";
        if (!StringUtils.isEmpty(title)) {
            sql += " and title like '%" + title + "%'";
            type += title;
        }
        if (!StringUtils.isEmpty(categoryid)) {
            if ("-1".equals(categoryid)) {
                sql += " and category is null";
            } else {
                sql += " and category =" + categoryid;
            }
            type += categoryid;
        }
        Page<Dbtable> data = Dbtable.dao.paginate(getPageIndex(type), 500, "select *", sql);
        setAttr("content_ids", content_ids);
        setAttr("table", table);
        setAttr("copyType", copyType);
        setAttr("data", data);
        setAttr("categoryid", categoryid);
        if ("category".equals(table)) {
            render("dbtable_list_checkboxdialog.html");
        } else {
            render("dbtable_list_dialog.html");
        }
    }

    @Override
    public void edit() {
        Integer id = getParaToInt("id");
        Dbtable img = Dbtable.dao.findById(id);
        setAttr("dbtable", img);
        render("dbtable_edit.html");
    }

    @Override
    public void save() {
        UploadFile uploadFile = getFile("cover");
        Dbtable us = getModel(Dbtable.class, "dbtable");
//        updateSysdict(us);
        if (us != null) {
            String tableName = us.getTablename();
            long id=0;
            try {
                 id= us.getId();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Dbtable dbtable = Dbtable.dao.findFirst("select * from dbtable where tablename = '" + tableName+"'"  );
            if (dbtable != null&&id==0) {
                try {
                    // TODO: 2018/1/23
//                    暂时缺少提示，
//                    HttpServletResponse response = getResponse();
//                    response.setContentType("text/html; charset=utf-8");
//                    PrintWriter writer = response.getWriter();
//                    writer.write("<script>layer.loa;</script>");
//                    writer.write("<script>window.close();</script>");
//                    writer.close();
//                    writer.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                if (us.getId() != null) {
                    us.update();
                } else if (us != null && us.getId() == null) {
                    us.save();
                }
            }
        }
        list();
    }

    private void updateSysdict(Dbtable dbtable) {
        String project_name = Config.getPropertiesValue("init.properties", "project_name");
        String password = Config.getPropertiesValue("init.properties", "password");
        String jdbcUrl1 = Config.getPropertiesValue("init.properties", "jdbcUrl1");
        String url_source = jdbcUrl1 + project_name + "?user=root&password=" + password + "&useUnicode=true&characterEncoding=UTF8";

        String tempJdbcUrl = dbtable.getJdbcurl();
        String tempJdbcPassword = dbtable.getJdbcpassword();
        String tempUsername = dbtable.getJdbcusername();
        String tempTablename = dbtable.getTablename();
        String url_destination = tempJdbcUrl + tempTablename + "?user=" + tempUsername + "&password=" + tempJdbcPassword + "&useUnicode=true&characterEncoding=UTF8";

    }

    @Override
    public void del() {
        String ids = getPara("ids");
        Db.update("delete from dbtable where id in (" + ids + ")");
        list();
    }

    public void updatedbs() {
//        由id可以
//        获取到表名，同步的数据
        String copyType = getPara("copyType");
        String dbtargets = getPara("table");
        String content_ids = getPara("content_ids");
        String ids = getPara("ids");
        String ui_checkbox = getPara("ui_checkbox");
        List<Dbtable> dbtables;
        if (ids.contains(content_ids + ",")) {
            if (StringUtils.isEmpty(content_ids)) {
//                    ids就是ids不需要更改
            } else {
                ids = ids.replace(content_ids + ",", "");
            }
        } else if (StringUtils.isEmpty(content_ids)) {
//                是表级别的同步
        } else {
//            要不没有选中同步的数据库，要不就出错
            renderText("error");
            return;
        }
        List<Adv> advs = new ArrayList<>();
        if ("copyByGender".equals(copyType) || ("copyByGenderCategory".equals(copyType))|| ("copyByGenderCategoryType".equals(copyType))) {
            advs = Adv.dao.find("select * from adv where id in (" + content_ids + ")");
        }
        dbtables = Dbtable.dao.find("select * from dbtable where id in (" + ids + ")");
//            password=bsmysqladmin
//            jdbcUrl1=jdbc:mysql://116.255.202.75/
        String project_name = Config.getPropertiesValue("init.properties", "project_name");
        String password = Config.getPropertiesValue("init.properties", "password");
        String jdbcUrl1 = Config.getPropertiesValue("init.properties", "jdbcUrl1");
        String url_source = jdbcUrl1 + project_name + "?user=root&password=" + password + "&useUnicode=true&characterEncoding=UTF8";
        for (Dbtable dbtable : dbtables
                ) {
            log.error("开始同步数据"+dbtables.size()+"个");
            synchronized (DbtableController.class) {
                String tempJdbcUrl = dbtable.getJdbcurl();
                String tempJdbcPassword = dbtable.getJdbcpassword();
                String tempUsername = dbtable.getJdbcusername();
                String tempProjectname = dbtable.getTablename();
                String url_destination = tempJdbcUrl + tempProjectname + "?user=" + tempUsername + "&password=" + tempJdbcPassword + "&useUnicode=true&characterEncoding=UTF8";
//                jdbc:mysql://127.0.0.1:3306/116.255.202.75
                log.error(tempProjectname+"开始同步数据："+url_destination);
                String url_clear = tempJdbcUrl.replace("jdbc:mysql://", "") + tempProjectname + "/api/clearCache";
                if (url_clear.contains("116.255.202.75")) {
                    url_clear = url_clear.replace("116.255.202.75", "https://qqh666.cn");
                } else if (url_clear.contains("47.94.153.3")) {
                    url_clear = url_clear.replace("47.94.153.3", "https://qqxy.b3ad.cn");
                }
                try {
                    if (!StringUtils.isEmpty(project_name) && !StringUtils.isEmpty(jdbcUrl1)) {
                        if (project_name.equals(tempProjectname) && jdbcUrl1.equals(tempJdbcUrl)) {
//                            如果该数据库是自己的话，continue跳过去
                            continue;
                        }
                    }
                    DbSychronizationController.init(url_source, url_destination, content_ids, dbtargets, copyType, url_clear, advs,ui_checkbox,tempProjectname);
                } catch (SQLException e) {
                    log.error(tempProjectname+"updatedbs SQLExceptionerror" + e.getMessage());
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    log.error(tempProjectname+"updatedbs InterruptedExceptionerror" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}
